package com.xiongjie.SingleLimit;

import com.xiongjie.SingleLimit.Interface.ISingleLimit;
import com.xiongjie.SingleLimit.service.SSingleLimitService;
import org.infinispan.Cache;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;

import java.util.concurrent.TimeUnit;

public class SingleLimitApplication {

    static final String[] names = {"Rome", "Como", "Basel"};

    private final EmbeddedCacheManager cacheManager;
    private final ISingleLimit iSingleCache;
    private Cache<String, String> cache;

    /**
     * 构造函数，创建缓存管理器和接口实现类
     */
    public SingleLimitApplication() {

        //自定义缓存并设置过期时间
        cacheManager = new DefaultCacheManager();
        ConfigurationBuilder config = new ConfigurationBuilder();
        config.expiration().lifespan(1, TimeUnit.MINUTES);
        cacheManager.defineConfiguration("singleLimit", config.build());
        cache = cacheManager.getCache("singleLimit");

        iSingleCache = initSingleCacheService(cache);
    }

    /**
     * 销毁缓存管理器
     */
    public void shutdown() {
        cacheManager.stop();
    }

    /**
     * 初始化接口实现类，重要的数据，在系统环境变量中设置
     *
     * @param cache
     * @return
     */
    private ISingleLimit initSingleCacheService(Cache<String, String> cache) {
        String apiKey = System.getenv("APIKEY");
        if (apiKey == null) {
            //这里应该是作为访问熔断的操作

            System.out.println("警告: APIKEY 环境变量没有设置,使用RSingleLimitService");
            return new SSingleLimitService(apiKey, cache);
        } else {
            return new SSingleLimitService(apiKey, cache);
        }
    }

    /**
     * 父类引用调用子类对象
     */
    public void getSingleLimitValue() {
        System.out.println("获取单机限流数据");

        long start = System.currentTimeMillis();

        for (String name : names) {
            String value = iSingleCache.getValueByName(name);
            System.out.println(String.format("%s - %s", name, value));
        }

        System.out.println(String.format("获取单机限流数据花费时间：%dms", System.currentTimeMillis() - start));
    }


    public static void main(String[] args) throws Exception {

        SingleLimitApplication app = new SingleLimitApplication();
        for (int i = 0; i < 30; i++) {
            app.getSingleLimitValue();
            Thread.sleep(100);
        }
        app.shutdown();
        System.exit(0);
    }
}
